package com.ebelter.bodyfatscale.ui.activity;


import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ebelter.bodyfatscale.R;
import com.ebelter.bodyfatscale.adapter.RegisterPagerAdapter;
import com.ebelter.bodyfatscale.common.AppDateLitConstants;
import com.ebelter.bodyfatscale.common.Constants;
import com.ebelter.bodyfatscale.model.Birthday;
import com.ebelter.bodyfatscale.model.UserInfo;
import com.ebelter.bodyfatscale.moudules.https.NetUtils;
import com.ebelter.bodyfatscale.moudules.https.interfaces.HttpResponse;
import com.ebelter.bodyfatscale.moudules.https.response.HttpsParameters;
import com.ebelter.bodyfatscale.moudules.https.response.OriginalParametersResponse;
import com.ebelter.bodyfatscale.ui.pager.register.BasePager;
import com.ebelter.bodyfatscale.ui.pager.register.BirthdayPager;
import com.ebelter.bodyfatscale.ui.pager.register.HeightPager;
import com.ebelter.bodyfatscale.ui.pager.register.RolePager;
import com.ebelter.bodyfatscale.ui.pager.register.SexPager;
import com.ebelter.bodyfatscale.util.KeyBoardShowListener;
import com.ebelter.bodyfatscale.util.NumUtils;
import com.ebelter.bodyfatscale.util.StringUtils;
import com.ebelter.bodyfatscale.util.ToastUtil;
import com.ebelter.bodyfatscale.util.UserSpUtil;
import com.ebelter.bodyfatscale.util.ViewUtils;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleUser;
import com.ebelter.btlibrary.util.ULog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class AddUserInfoActivity extends BaseActivity implements ViewPager.OnPageChangeListener {




    private static final String TAG="AddUserInfoActivity";
    public static final int REQUEST_CODE = 77;


    @BindView(R.id.iv_back_register)
    ImageView iv_back_register;

    @BindView(R.id.vp_register)
    ViewPager vpRegister;

    @BindView(R.id.btn_next_register)
    TextView btn_next_register;

    private List<BasePager> pagers;
    private int curIndex;

    private int mHeight = 176;
    private int mSex = 0;//0男1女
    private Birthday mBirthday;
    private int roleFlag;//是否运动员标志 0工人 1运动员


    KeyBoardShowListener keyBoardShowListener = new KeyBoardShowListener(this);


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_writeguestinfo;
    }

    @Override
    protected void initViews() {


        //监听软键盘的状态
        keyBoardShowListener.setKeyboardListener(

                new KeyBoardShowListener.OnKeyboardVisibilityListener() {
                    @Override
                    public void onVisibilityChanged(boolean visible) {
                        if (visible) {
                            //软键盘已弹出
                            ULog.e(TAG,"----------软键盘已弹出");
                            ViewUtils.hideView(btn_next_register);

                        } else {
                            //软键盘未弹出
                            ULog.e(TAG,"----------软键盘未弹出");
                            ViewUtils.displayView(btn_next_register);
                        }
                    }
                }, AddUserInfoActivity.this);


    }

    @Override
    protected void initData() {

        if (pagers == null) {
            pagers = new ArrayList<>();
        } else {
            pagers.clear();
        }
        pagers.add(new HeightPager(this,mHeight));
        pagers.add(new SexPager(this,mSex));
        pagers.add(new BirthdayPager(this));
        pagers.add(new RolePager(this));

        vpRegister.setAdapter(new RegisterPagerAdapter(pagers));
        vpRegister.setOffscreenPageLimit(pagers.size());
        vpRegister.addOnPageChangeListener(this);


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ULog.i(TAG,"------点击了返回键-------");

    }


    public void done(boolean isAthlete){
        ULog.i(TAG,"---done----");

        HeightPager heightPager = (HeightPager) pagers.get(0);

        mHeight = heightPager.getHeight();

        SexPager sexPager = (SexPager) pagers.get(1);

        mSex = sexPager.getSexValue();

        BirthdayPager birthdayPager = (BirthdayPager) pagers.get(2);


        mBirthday=birthdayPager.getBirthday();

        ULog.i(TAG,"----Height = "+mHeight+"-----Sex = "+sexPager.getSexValue()+"----mBirthday = "+mBirthday.getFatterDay()+"----isAthlete = "+isAthlete);

        if (mHeight< AppDateLitConstants.HEIGHT_MIN||mHeight>AppDateLitConstants.HEIGHT_MAX){
            ToastUtil.show(R.string.Please_enter_a_value_between_20_and_250_height);
            return;
        }


        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        final Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(HttpsParameters.USER_ID, UserSpUtil.readLong(Constants.IUser.USER_ID));
        paramMap.put(HttpsParameters.HEIGHT, mHeight);
        paramMap.put(HttpsParameters.SEX, mSex);
        paramMap.put(HttpsParameters.BIRTHDAY, mBirthday.getFatterDay());
        paramMap.put(HttpsParameters.PROFESSION, isAthlete?1:0);//0工人 1运动员





        NetUtils.getInstance().updateInfo(AddUserInfoActivity.this, paramMap, new HttpResponse<OriginalParametersResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, OriginalParametersResponse originalParametersResponse) {
                ULog.i(TAG,"当前线程："+Thread.currentThread().getName());
                if (isRequestSuccess){

                    if (originalParametersResponse.resultCode==0){
                        ToastUtil.show(R.string.Modify_Success);
                        updateLocalData((Map<String, Serializable>) originalParametersResponse.originalParameters);
                        printUerInfo();
                        finish();

                    }else if (originalParametersResponse.resultCode==112){
                        ToastUtil.show(R.string.nickname_have_been_registered);
                    }else if (originalParametersResponse.resultCode==110){
                        ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                    }else {
                        ToastUtil.show(R.string.Modify_Failed);
                    }

                }else {
                    ToastUtil.show(R.string.Network_connection_error);
                }
            }
        });

    }


    private void printUerInfo(){
        long userid = UserSpUtil.readLong(Constants.IUser.USER_ID);
        int height = UserSpUtil.readInt(Constants.IUser.HEIGHT);
        int sex = UserSpUtil.readInt(Constants.IUser.SEX);
        int pro = UserSpUtil.readInt(Constants.IUser.PROFESSION);
        String bir = UserSpUtil.readString(Constants.IUser.BIRTHDAY);
        int year = UserSpUtil.readInt(Constants.IUser.YEAR);
        int mon = UserSpUtil.readInt(Constants.IUser.MONTHS);
        int day = UserSpUtil.readInt(Constants.IUser.DAY);
        int age = UserSpUtil.readInt(Constants.IUser.AGE);

        ULog.i(TAG,"--userid="+userid+"---height"+height+"---sex="+sex+
                "--pro="+pro+"---bir"+bir+"---year="+year+
                "--mon="+mon+"---day"+day+"---age="+age

        );





    }


    //更新本地数据
    private void updateLocalData(Map<String, Serializable> originalParameters) {
        if (originalParameters==null){
            return;
        }
        Set<String> sets = originalParameters.keySet();
        for (String k:sets){
            if (TextUtils.isEmpty(k)){
                continue;
            }
            Serializable serializable = originalParameters.get(k);
            if (TextUtils.equals(HttpsParameters.HEIGHT,k)){
                //说明更改了身高
                UserSpUtil.writeInt(Constants.IUser.HEIGHT, (int)serializable);
            }else if (TextUtils.equals(HttpsParameters.SEX,k)){
                UserSpUtil.writeInt(Constants.IUser.SEX, (int) serializable);
            }else if (TextUtils.equals(HttpsParameters.BIRTHDAY,k)){


                UserSpUtil.writeString(Constants.IUser.BIRTHDAY, (String) serializable);
                int year=getBirthdayIntValue((String) serializable,0,1990);
                UserSpUtil.writeInt(Constants.IUser.YEAR,year);

                int mon=getBirthdayIntValue((String) serializable,1,6);
                UserSpUtil.writeInt(Constants.IUser.MONTHS,mon);

                int day=getBirthdayIntValue((String) serializable,2,1);
                UserSpUtil.writeInt(Constants.IUser.DAY,day);

                UserSpUtil.writeInt(Constants.IUser.AGE,getAgeByBirthday(year));
                ScaleUser.getUser().setAge(getAgeByBirthday(year));



            }else if (TextUtils.equals(HttpsParameters.PROFESSION,k)){
                UserSpUtil.writeInt(Constants.IUser.PROFESSION, (int) serializable);
            }
        }
    }


    private int getBirthdayIntValue(String string,int index,int defaultValue){
        if (TextUtils.isEmpty(string)){
            return defaultValue;
        }
        String[] args = string.split("-");
        if (args.length!=3){
            return defaultValue;
        }
        return NumUtils.string2Int(args[index],defaultValue);
    }

    private int getAgeByBirthday(int year){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR)-year;
    }



    @OnClick({R.id.iv_back_register, R.id.btn_next_register})
    public void btClick(View view) {
        int index = curIndex;
        switch (view.getId()) {
            case R.id.iv_back_register:
                index--;
                if (index < 0) {
                    finish();
                    return;
                }
                break;
            case R.id.btn_next_register:
                if (curIndex==0){
                    HeightPager heightPager = (HeightPager) pagers.get(0);
                    int height = heightPager.getHeight();
                    if (height>= AppDateLitConstants.HEIGHT_MIN&&height<=AppDateLitConstants.HEIGHT_MAX){
                    }else {
                        ToastUtil.showGravity(R.string.Please_enter_a_value_between_20_and_250_height, Gravity.CENTER);
                        return;
                    }
                }
                index++;
                if (index >= pagers.size()) index = pagers.size()-1;
                break;
        }
        vpRegister.setCurrentItem(index);
        curIndex = index;
        setNextBtText(curIndex);
        if (curIndex==pagers.size()-1){
            ViewUtils.goneView(btn_next_register);
        }else {
            ViewUtils.displayView(btn_next_register);
        }

    }

    private void setNextBtText(int curIndex) {
        btn_next_register.setText(curIndex < 3 ? getString(R.string.next) : getString(R.string.done));
    }
    //设置下一步按钮是否可以用
    public void setbtn_next_register(boolean enable){
        btn_next_register.setEnabled(enable);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) { //屏蔽返回键
            btClick(iv_back_register);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
